{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Administrator\\Anaconda3\\lib\\requests\\__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.11) or chardet (3.0.4) doesn't match a supported version!\n",
      "  RequestsDependencyWarning)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "matchzoo version 1.0.2\n",
      "`ranking_task` initialized with metrics [normalized_discounted_cumulative_gain@3(0.0), normalized_discounted_cumulative_gain@5(0.0), mean_average_precision(0.0)]\n",
      "data loading ...\n",
      "data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`\n",
      "停用表配置成功\n"
     ]
    }
   ],
   "source": [
    "%run init.ipynb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "preprocessor = mz.models.MatchLSTM.get_default_preprocessor()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval:   0%| | 0/96 [00:00<?, ?it/s]Building prefix dict from the default dictionary ...\n",
      "Loading model from cache C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\jieba.cache\n",
      "Loading model cost 1.409 seconds.\n",
      "Prefix dict has been built succesfully.\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 96/96 [00:01<00:00, 49.23it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 91/91 [00:00<00:00, 192.09it/s]\n",
      "Processing text_right with append: 100%|████████████████████████████████████████████| 91/91 [00:00<00:00, 30347.59it/s]\n",
      "Building FrequencyFilter from a datapack.: 100%|████████████████████████████████████| 91/91 [00:00<00:00, 45754.22it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 91/91 [00:00<00:00, 30432.28it/s]\n",
      "Processing text_left with extend: 100%|█████████████████████████████████████████████| 96/96 [00:00<00:00, 13712.48it/s]\n",
      "Processing text_right with extend: 100%|████████████████████████████████████████████| 91/91 [00:00<00:00, 45514.15it/s]\n",
      "Building Vocabulary from a datapack.: 100%|██████████████████████████████████████| 887/887 [00:00<00:00, 887487.51it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 96/96 [00:00<00:00, 195.23it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 91/91 [00:00<00:00, 194.14it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 91/91 [00:00<00:00, 30333.12it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 96/96 [00:00<00:00, 32043.07it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 91/91 [00:00<00:00, 15223.42it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 96/96 [00:00<00:00, 95733.04it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 91/91 [00:00<00:00, 30354.83it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 50/50 [00:00<00:00, 191.67it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 50/50 [00:00<00:00, 198.52it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 50/50 [00:00<00:00, 16678.48it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 50/50 [00:00<00:00, 16658.61it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 50/50 [00:00<00:00, 25019.71it/s]\n",
      "Processing length_left with len: 100%|███████████████████████████████████████████████| 50/50 [00:00<00:00, 8338.25it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 50/50 [00:00<00:00, 12502.40it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 29/29 [00:00<00:00, 171.69it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 29/29 [00:00<00:00, 196.03it/s]\n",
      "Processing text_right with transform: 100%|██████████████████████████████████████████| 29/29 [00:00<00:00, 9671.21it/s]\n",
      "Processing text_left with transform: 100%|███████████████████████████████████████████| 29/29 [00:00<00:00, 9685.07it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 29/29 [00:00<00:00, 29050.59it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 29/29 [00:00<00:00, 29155.04it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 29/29 [00:00<00:00, 14540.92it/s]\n"
     ]
    }
   ],
   "source": [
    "train_pack_processed = preprocessor.fit_transform(train_pack_raw)\n",
    "dev_pack_processed = preprocessor.transform(dev_pack_raw)\n",
    "test_pack_processed = preprocessor.transform(test_pack_raw)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'embedding_input_dim': 318,\n",
       " 'filter_unit': <mzcn.preprocessors.units.frequency_filter.FrequencyFilter at 0x2597e9dfac8>,\n",
       " 'vocab_size': 318,\n",
       " 'vocab_unit': <mzcn.preprocessors.units.vocabulary.Vocabulary at 0x2597e9ff278>}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "preprocessor.context"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# glove_embedding = mz.datasets.embeddings.load_glove_embedding(dimension=300)\n",
    "# term_index = preprocessor.context['vocab_unit'].state['term_index']\n",
    "# embedding_matrix = glove_embedding.build_matrix(term_index)\n",
    "# l2_norm = np.sqrt((embedding_matrix * embedding_matrix).sum(axis=1))\n",
    "# embedding_matrix = embedding_matrix / l2_norm[:, np.newaxis]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "trainset = mz.dataloader.Dataset(\n",
    "    data_pack=train_pack_processed,\n",
    "    mode='pair',\n",
    "    num_dup=2,\n",
    "    num_neg=1\n",
    ")\n",
    "devset = mz.dataloader.Dataset(\n",
    "    data_pack=dev_pack_processed\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "padding_callback = mz.models.MatchLSTM.get_default_padding_callback()\n",
    "\n",
    "trainloader = mz.dataloader.DataLoader(\n",
    "    dataset=trainset,\n",
    "    stage='train',\n",
    "    callback=padding_callback,\n",
    ")\n",
    "devloader = mz.dataloader.DataLoader(\n",
    "    dataset=devset,\n",
    "    stage='dev',\n",
    "    callback=padding_callback,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MatchLSTM(\n",
      "  (embedding): Embedding(318, 100, padding_idx=0)\n",
      "  (dropout): Dropout(p=0.2, inplace=False)\n",
      "  (input_proj): StackedBRNN(\n",
      "    (rnns): ModuleList(\n",
      "      (0): LSTM(100, 100, bidirectional=True)\n",
      "    )\n",
      "  )\n",
      "  (match_module): MatchModule(\n",
      "    (v2_proj): Linear(in_features=200, out_features=200, bias=True)\n",
      "    (proj): Linear(in_features=800, out_features=400, bias=True)\n",
      "    (dropout): Dropout(p=0.2, inplace=False)\n",
      "  )\n",
      "  (mlstm_module): StackedBRNN(\n",
      "    (rnns): ModuleList(\n",
      "      (0): LSTM(400, 100, bidirectional=True)\n",
      "    )\n",
      "  )\n",
      "  (classification): Sequential(\n",
      "    (0): Dropout(p=0.2, inplace=False)\n",
      "    (1): Linear(in_features=200, out_features=200, bias=True)\n",
      "    (2): Tanh()\n",
      "  )\n",
      "  (out): Linear(in_features=200, out_features=1, bias=True)\n",
      ") 996001\n"
     ]
    }
   ],
   "source": [
    "model = mz.models.MatchLSTM()\n",
    "\n",
    "model.params['task'] = ranking_task\n",
    "model.params['mask_value'] = 0\n",
    "# model.params['embedding'] = embedding_matrix #这里是当加载glove等模型时取消该行注释\n",
    "#设置embedding系数\n",
    "model.params[\"embedding_output_dim\"]=100\n",
    "model.params[\"embedding_input_dim\"]=preprocessor.context[\"embedding_input_dim\"]\n",
    "\n",
    "model.build()\n",
    "\n",
    "print(model, sum(p.numel() for p in model.parameters() if p.requires_grad))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "optimizer = torch.optim.Adadelta(model.parameters())\n",
    "\n",
    "trainer = mz.trainers.Trainer(\n",
    "    model=model,\n",
    "    optimizer=optimizer,\n",
    "    trainloader=trainloader,\n",
    "    validloader=devloader,\n",
    "    validate_interval=None,\n",
    "    epochs=10\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "7595748fc29f46f0abae8444e6c9711d",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-1 Loss-0.985]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1818 - normalized_discounted_cumulative_gain@5(0.0): 0.1818 - mean_average_precision(0.0): 0.1818\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d194d3cb455d45018e6ed4dbcd6711a8",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-2 Loss-0.998]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1818 - normalized_discounted_cumulative_gain@5(0.0): 0.1818 - mean_average_precision(0.0): 0.1818\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "821f0648d763400a9aae0d5a4eec6289",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-3 Loss-0.983]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1818 - normalized_discounted_cumulative_gain@5(0.0): 0.1818 - mean_average_precision(0.0): 0.1818\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "02eb8d99a9784be3acc7fcf56358a43c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-4 Loss-0.979]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1818 - normalized_discounted_cumulative_gain@5(0.0): 0.1818 - mean_average_precision(0.0): 0.1818\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "af5092b88a3a41b992e62748c0bab82b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-5 Loss-0.960]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1818 - normalized_discounted_cumulative_gain@5(0.0): 0.1818 - mean_average_precision(0.0): 0.1818\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e406c7317aef4e68af971b8ca590e889",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-6 Loss-0.882]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1818 - normalized_discounted_cumulative_gain@5(0.0): 0.1818 - mean_average_precision(0.0): 0.1818\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "058ed0937cd84cd4b80d0d8093cb674f",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-7 Loss-0.797]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1818 - normalized_discounted_cumulative_gain@5(0.0): 0.1818 - mean_average_precision(0.0): 0.1818\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "0a3f5ff61a45425cb777473edfdf52bf",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-8 Loss-0.404]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1818 - normalized_discounted_cumulative_gain@5(0.0): 0.1818 - mean_average_precision(0.0): 0.1818\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b41bf3d937244829bb7cb9a4cc618ff3",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-9 Loss-0.208]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1818 - normalized_discounted_cumulative_gain@5(0.0): 0.1818 - mean_average_precision(0.0): 0.1818\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "03bdf44f85ef427392754324c84adddb",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-10 Loss-0.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1818 - normalized_discounted_cumulative_gain@5(0.0): 0.1818 - mean_average_precision(0.0): 0.1818\n",
      "\n",
      "Cost time: 5.442551612854004s\n"
     ]
    }
   ],
   "source": [
    "trainer.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "983"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gc\n",
    "gc.collect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
